package com.xbb.monitor.service;

import com.xbb.monitor.entity.LoadAverage;
import com.xbb.monitor.entity.echarts.AreaStyle;
import com.xbb.monitor.entity.echarts.LineBean;
import com.xbb.monitor.entity.echarts.Normal;
import com.xbb.monitor.repository.LoadAverageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class LoadAverageService {
    @Autowired
    private LoadAverageRepository loadAverageRepository;
    @PersistenceContext
    private EntityManager entityManager;

    public List<LineBean> getData(Calendar calendar, int interval, SimpleDateFormat sdf){
        String sql = "SELECT id, first, second, third, time FROM (\n" +
                "  SELECT b.*,@rownum \\:= @rownum + 1 AS rownum,\n" +
                "  @ptime2 \\:=b.time as ptime2,\n" +
                "  if(TIMESTAMPDIFF(MINUTE,@ptime,b.time)<?2,@ptime=null,@ptime\\:=@ptime2) AS ptime FROM\n" +
                "(SELECT * FROM t_load_average WHERE TIME >= ?1  ORDER BY time) b,\n" +
                "(SELECT @rownum \\:= 0,@ptime\\:= NULL ,@rank\\:=0,@ptime2\\:=NULL ) a\n" +
                ") AS c WHERE ptime IS NOT NULL";

        Query query = entityManager.createNativeQuery(sql,LoadAverage.class);
        query.setParameter(1,calendar.getTime());
        query.setParameter(2,interval);
        List<LoadAverage> loadAverages = query.getResultList();

        List<LineBean> lineBeans = new ArrayList<LineBean>();
        LineBean lineFirst = new LineBean("first","line");
        LineBean lineSecond = new LineBean("second","line");
        LineBean lineThird = new LineBean("third","line");

        List<String[]> datasFirst = new ArrayList<String[]>();
        List<String[]> datasSecond = new ArrayList<String[]>();
        List<String[]> datasThird = new ArrayList<String[]>();

        for(LoadAverage loadAverage : loadAverages){
            String[] dataFirst = {sdf.format(loadAverage.getTime()),loadAverage.getFirst()+""};
            String[] dataSecond = {sdf.format(loadAverage.getTime()),loadAverage.getSecond()+""};
            String[] dataThird = {sdf.format(loadAverage.getTime()),loadAverage.getThird()+""};

            datasFirst.add(dataFirst);
            datasSecond.add(dataSecond);
            datasThird.add(dataThird);
        }

        lineFirst.setData(datasFirst);
        lineSecond.setData(datasSecond);
        lineThird.setData(datasThird);

        lineBeans.add(lineFirst);
        lineBeans.add(lineSecond);
        lineBeans.add(lineThird);

        return lineBeans;
    }
}
